<template>
    <div class="score-rules">
        <a-button type="primary" class="btn-add" @click="onAdd">新增</a-button>
        <a-table :columns="columns" :data-source="list" rowKey="id"
            bordered
            :loading="loading"
            :pagination="pagination"
            @change="onPageChange"
        >
            <span slot="ruleType"  slot-scope="text">{{getRuleType(text)}}</span>
            <span slot="scoringRules"  slot-scope="text">{{getScoringType(text)}}</span>
            <span slot="description"  slot-scope="text">{{text || '-'}}</span>
            <span slot="action" slot-scope="text, record">
                <span class="action-btn" @click="onEdit(record)">修改</span>
                <span class="action-btn" @click="onDetele(record.id)">删除</span>
            </span>
        </a-table>
        <a-modal :visible="visible" :footer="null"
            :title="type==='add'?'新增打分系数':'修改打分系数'"
            @cancel="onCancel"
        >
            <a-form :form="form" @submit="onSubmit">
                <a-form-item label="打分类别"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                >
                    <a-select placeholder="请选择打分类别"
                        @change="onChangeRuleType"
                        v-decorator="['ruleType',
                            { rules: [
                                { required: true, message: '请选择打分类别' },
                            ] }
                        ]"
                    >
                        <a-select-option v-for="(item, index) in ruleTypeList" :key="index"
                            :value="item.value"
                        >{{item.label}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="职务"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                    v-show="ruleType"
                >
                    <a-select placeholder="请选择职务"
                        v-decorator="['roleName',
                            { rules: [
                                { required: true, message: '请选择职务' },
                            ] }
                        ]"
                    >
                        <a-select-option v-for="(item, index) in roleList" :key="index"
                            :value="item.id"
                        >{{item.name}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="评分类别"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                >
                    <a-input placeholder="请输入评分类别"
                        v-decorator="['ratingDescription',
                            { rules: [
                                { required: true, message: '请输入评分类别' },
                            ] }
                        ]"
                    />
                </a-form-item>
                <a-form-item label="评分描述"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                >
                    <a-textarea placeholder="请输入评分描述" :rows="3" 
                        v-decorator="['description',
                            { rules: [
                                { required: true, message: '请输入评分描述' },
                            ] }
                        ]"
                    />
                </a-form-item>
                <!-- <a-form-item label="单项总分"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                >
                    <a-input-number :min="1" :max="100"  placeholder="系数"
                        v-decorator="['totalScore',
                            { rules: [
                                { required: true, message: '请填写打分系数' },
                            ] }
                        ]"
                    />
                </a-form-item> -->
                <a-form-item :wrapper-col="{offset: 6}">
                    <a-button type="primary" html-type="submit" :loading="addLoading">提交</a-button>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script>
import { getScoredType, getRoles, addScoredType, updateScoredType, deleteScoredType } from '@/services';

const columns = [
    { title: '打分类别', dataIndex: 'ruleType', scopedSlots: { customRender: 'ruleType' }},
    { title: '职务', dataIndex: 'roleName' },
    { title: '评分类别', dataIndex: 'ratingDescription' },
    { title: '评分描述', dataIndex: 'description', scopedSlots: { customRender: 'description' } },
    // { title: '单项总分', dataIndex: 'totalScore' },
    { title: '操作', key: 'action', align: 'center', scopedSlots: { customRender: 'action' } },
]

const ruleTypeList = [
    { value: 0, label: '部门' },
    { value: 1, label: '个人' },
]

const scoringRulesType = [
    { value: 'superiorScore', label: '上级打分' },
    { value: 'subordinateScore', label: '下属打分' },
    { value: 'peersScore', label: '同级打分' },
    { value: 'selfScore', label: '自我打分' },
]

export default {
    name: 'ScoreRules',
    data(){
        return {
            scoringRulesType,
            ruleTypeList,
            visible: false,
            addLoading: false,
            type: 'add',
            formItemLayout: {
                labelCol: { span: 6 },
                wrapperCol: { span: 16 },
            },
            form: this.$form.createForm(this),
            columns,
            loading: false,
            list: [],
            pagination: {},
            roleList: [],
            editId: '',
            ruleType: 1
        }
    },
    mounted(){
        this.getRulesList();
        this.getAllRoles();
    },
    methods: {
        // 切换打分类型
        onChangeRuleType(type){
            // console.log(type)
            this.ruleType = type
        },
        // 新增按钮
        onAdd(){
            this.visible = true;
            this.type = "add"
        },
        // 关闭modal
        onCancel(){
            this.ruleType = 1;
            this.visible = false;
            this.form.resetFields();
        },
        // 删除按钮
        onDetele(id){
            const _that = this;
            this.$confirm({
                title: `确认删除这条 打分系数 吗? `,
                okText: "删除",
                okType: 'danger',
                cancelText: "取消",
                onOk(){
                    _that.deleteKpiRule(id)
                }
            })
        },
        // 切换分页
        onPageChange(pagination, filters, sorter){
            let { current, pageSize } = pagination;
            this.getRulesList(current);
        },
        // 获取打分系数列表
        async getRulesList(page=1){
            this.loading = true;
            let res = await getScoredType({ page });
            this.loading = false;
            if(res.responseObject){
                let { count, data } = res.responseObject;
                this.list = data;
                let pagination = { ...this.pagination };
                pagination.total = count;
                pagination.current = page;
                pagination.pageSize = 10;
                pagination.showTotal = (total, range) => `共找到 ${total} 条数据`
                this.pagination = pagination;
            }
        },
        // 获取所有职务列表
        async getAllRoles(){
            let res = await getRoles({ pageSize: 99 });
            if(res.responseObject) {
                this.roleList = res.responseObject.Result
            }
        },
        // 修改按钮
        onEdit(params){
            this.form.getFieldDecorator('ruleType');
            this.form.getFieldDecorator('roleName');
            this.form.getFieldDecorator('ratingDescription');
            // this.form.getFieldDecorator('totalScore');
            this.form.getFieldDecorator('description');
            this.type = 'edit';
            this.visible = true;
            this.ruleType = params.ruleType || 0;
            this.editId = params.id;
            this.form.setFieldsValue({
                ruleType: params.ruleType === 0 ? 0 : 1,
                ratingDescription: params.ratingDescription,
                // totalScore: params.totalScore,
                roleName: params.ruleType === 0 ? '无' : params.ruleType,
                description: params.description
            })
        },
        // 打分类别
        getRuleType(type){
            if(type === 0) return '部门';
            else return '个人';
        },
        // 打分类型
        getScoringType(type){
            if(type === 'superiorScore') return '上级打分';
            else if(type === 'subordinateScore') return '下属打分';
            else if(type === 'peersScore') return '同级打分';
            else if(type === 'selfScore') return '自我打分';
        },
        // 提交按钮
        onSubmit(e){
            e.preventDefault();
            const _that = this;
            const { type, editId } = this;
            this.form.validateFields((err, values) => {
                if (!err) {
                    let { ruleType, roleName, ratingDescription, totalScore, description } = values;
                    if(ruleType && roleName === '无') {
                        _that.$message.error('请先选择部门', 1);
                        return;
                    }
                    let item = _that.roleList.filter(item => item.id === roleName);
                    let data = {
                        ratingDescription,
                        // totalScore,
                        ruleType: ruleType === 1 ? roleName : 0,
                        roleName: item[0] && ruleType === 1 ? item[0].name : '无',
                        description
                    };
                    // 新增
                    if(type === 'add') _that.onAddRules(data);
                    if(type === 'edit') {
                        _that.updateRule(Object.assign(data, { id: editId }))
                    }
                }
            })
        },
        // 新增打分规则
        async onAddRules(params){
            this.addLoading = true;
            let res = await addScoredType(params);
            this.addLoading = false;
            const _that = this;
            if(res.success) {
                this.$message.success('新增打分系数成功', 1, ()=>{
                    _that.onCancel();
                    _that.getRulesList(_that.pagination.current);
                })
            }else if(!res.success && res.errorMessage){
                this.$message.error(res.errorMessage, 1)
            }
        },
        // 修改打分规则
        async updateRule(params){
            this.addLoading = true;
            let res = await updateScoredType(params);
            this.addLoading = false;
            const _that = this;
            if(res.success) {
                this.$message.success('修改打分系数成功', 1, ()=>{
                    _that.onCancel();
                    _that.getRulesList(_that.pagination.current);
                })
            }else if(!res.success && res.errorMessage){
                this.$message.error(res.errorMessage, 1)
            }
        },
        // 删除规则
        async deleteKpiRule(id){
            this.loading = true;
            let res = await deleteScoredType(id);
            const _that = this;
            if(res.success){
                this.$message.success('删除打分系数成功', 1, ()=>{
                    _that.getRulesList(_that.pagination.count > 11 ? _that.pagination.current : 1);
                })
            }else if(res.errorMessage){
                this.loading = false;
                this.$message.error(res.errorMessage, 1)
            }
        }
    }
}
</script>
<style lang="less" scoped>
@import '../global.less';
    .score-rules{
        padding: 20px;
        .btn-add{
            margin-bottom: 20px;
        }
        .action-btn{
            color: @primary;
            margin: 0 10px;
            cursor: pointer;
        }
    }
</style>